const app = getApp();
const WECHAT_MAX_NUMBER = 3; //微信打水配置的最大数量
const ALIPAY_MAX_NUMBER = 3; //支付宝打水配置的最大数量
const limits = [{
  value: 2,
  name: "永久有效"
}, {
  value: 1,
  name: "有效时间"
}];
let timer;
Page({
  data: {
    base_thrash_config: { //基础打水配置
      rise: '',
      money: ''
    },
    card_thrash_config: { //刷卡打水配置
      rise: "",
      money: "",
      withholding_fee_rise: 7.5,
    },
    coin_thrash_config: { //投币打水配置
      rise: "",
      money: "",
      coin_upper_limit: 10,
      withholding_fee_rise: 7.5,
    },
    wechat_thrash_config: [ //微信打水配置
      {
        rise: 1,
        money: "",
        is_default: true,
      }, {
        rise: 7.5,
        money: "",
        is_default: true,
      }, {
        rise: 18.9,
        money: "",
        is_default: true,
      }
    ],
    alipay_thrash_config: [ //支付宝打水配置
      {
        rise: 1,
        money: "",
        is_default: true,
      }, {
        rise: 7.5,
        money: "",
        is_default: true,
      }, {
        rise: 18.9,
        money: "",
        is_default: true,
      }
    ],

    wechat_max_number: WECHAT_MAX_NUMBER,
    alipay_max_number: ALIPAY_MAX_NUMBER,
    is_unfold: false, //是否展开 默认不展开
    template_title: "", //模板名称
    limits,
    mode: 1,
    type: 2,
    end_time: "",
    start_time: '',
    currentLimit: 0, //选中的有效期
    template_status: 1, //状态，1：开启，2：关闭
    price_config: [{
      recharge: "",
      give: ""
    }], //金额配置
    template: "",
    tips: false,
    tipsContent: '',
    isTapSyncPrice: false, //是否点击过同步价格
    isFranchiser: false, //是否是加盟商
    franchisers: [], //合伙人的加盟商
    franchiserIndex: "", //选中的加盟商
    disabled: false,
  },



  onLoad: function (options) {
    //type模版种类，1：充值（充M送N），2：设备（售水参数），3：合伙人充值模版（充M送N)
    //mode 模式  1添加 2编辑
    this.from = options.from || ''; //是否来自middle下的template
    let type = options.type || 2;
    let isFranchiser = options.is_franchiser || false;
    let mode = options.id ? 2 : 1; //2编辑 1添加
    this.id = options.id || "";
    this.partner_id = options.partner_id || '';

    if (mode == 2) {
      let _self = this;
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('openTemplateAdd', function (data) {
        if (type == 1 || type == 3) {
          _self.getFranchisers(data.partner_id);
          let index = _self.data.limits.findIndex(item => item.value == data.template_type);
          _self.setData({
            template_status: data.template_status,
            currentLimit: index,
            template_title: data.template_title,
            start_time: data.template_type == 1 ? _self.formatTime(data.start_time) : '',
            end_time: data.template_type == 1 ? _self.formatTime(data.end_time) : '',
            price_config: data.template
          })
        } else {
          _self.getFranchisers(data.partner_id);
          let index = _self.data.limits.findIndex(item => item.value == data.template_type);
          let card_thrash_config = {
            rise: data.template_whole.card ? data.template_whole.card.rise : '',
            money: data.template_whole.card ? data.template_whole.card.money : '',
            withholding_fee_rise: data.template_whole.card ? data.template_whole.card.water_quantity : _self.data.card_thrash_config.withholding_fee_rise
          }
          let coin_thrash_config = {
            rise: data.template_whole.coin ? data.template_whole.coin.rise : '',
            money: data.template_whole.coin ? data.template_whole.coin.money : '',
            coin_upper_limit: data.template_whole.coin ? data.template_whole.coin.coin_money : _self.data.coin_thrash_config.coin_upper_limit,
            withholding_fee_rise: data.template_whole.coin ? data.template_whole.coin.water_quantity : _self.data.coin_thrash_config.withholding_fee_rise
          }
          _self.setData({
            is_unfold: true,
            wechat_thrash_config: data.template_whole.wx ? data.template_whole.wx : _self.data.wechat_thrash_config,
            alipay_thrash_config: data.template_whole.al ? data.template_whole.al : _self.data.alipay_thrash_config,
            card_thrash_config,
            coin_thrash_config,
            base_thrash_config: Object.assign(_self.data.base_thrash_config, data.base_price),
            template_status: data.template_status,
            currentLimit: index,
            template_title: data.template_title,
            start_time: data.template_type == 1 ? _self.formatTime(data.start_time) : '',
            end_time: data.template_type == 1 ? _self.formatTime(data.end_time) : '',
          })
        }
        console.log(data)
      })
    }
    const titles = ["用户自助充值模板", "价格模板", "代客充值模板"];
    let title = `${mode==1?'新增':'编辑'}${titles[type-1]}`;
    wx.setNavigationBarTitle({
      title,
    })
    this.setData({
      mode,
      type,
      isFranchiser,
      disabled: this.partner_id ? true : false,
    });
    if (mode == 1 && isFranchiser) {
      this.getFranchisers(this.partner_id);
    }
  },


  onUnload: function () {
    clearTimeout(timer);
  },


  handleCommonInput(e, config) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`${config}.${name}`]: e.detail.value
    })
  },

  //基础打水配置数据输入
  handleBaseThrashConfig(e) {
    this.handleCommonInput(e, "base_thrash_config")
  },

  //水卡打水配置输入
  handleCardThrashInput(e) {
    this.handleCommonInput(e, "card_thrash_config")
  },

  //投币打水配置输入
  handleCoinThrashInput(e) {
    this.handleCommonInput(e, "coin_thrash_config")
  },

  //微信打水配置输入
  handleWechatThrashInput(e) {
    const dataset = e.currentTarget.dataset;
    this.setData({
      [`wechat_thrash_config[${dataset.index}].${dataset.name}`]: e.detail.value
    })
  },

  addWechatThrashConfig() {
    const wechat_thrash_config = this.data.wechat_thrash_config;
    wechat_thrash_config.push({
      rise: '',
      money: ''
    });
    this.setData({
      wechat_thrash_config
    })
  },

  subtractWechatThrashConfig(e) {
    const index = e.currentTarget.dataset.index;
    const wechat_thrash_config = this.data.wechat_thrash_config;
    wechat_thrash_config.splice(index, 1)
    this.setData({
      wechat_thrash_config
    });
  },

  //支付宝打水配置输入
  handleAlipayThrashInput(e) {
    const dataset = e.currentTarget.dataset;
    this.setData({
      [`alipay_thrash_config[${dataset.index}].${dataset.name}`]: e.detail.value
    })
  },

  addAlipayThrashConfig() {
    const alipay_thrash_config = this.data.alipay_thrash_config;
    alipay_thrash_config.push({
      rise: '',
      money: ''
    });
    this.setData({
      alipay_thrash_config
    })
  },

  subtractAlipayThrashConfig(e) {
    const index = e.currentTarget.dataset.index;
    const alipay_thrash_config = this.data.alipay_thrash_config;
    alipay_thrash_config.splice(index, 1)
    this.setData({
      alipay_thrash_config
    });
  },




  //基础价格的同步价格
  syncPrice(e) {
    let type = e.currentTarget.dataset.type || 'all';
    const base_thrash_config = this.data.base_thrash_config;
    if (base_thrash_config.rise == "") {
      app.showToast("请配置基础价格打水量");
      return;
    }
    if (base_thrash_config.money == "") {
      app.showToast("请配置价格金额");
      return;
    }
    if (type == "all") {
      wx.showModal({
        content: "此操作将基础价格同步到刷卡、投币、微信、支付宝配置,确认同步？",
        success: res => {
          if (res.confirm) {
            this.syncPriceOperate(base_thrash_config, type);
          }
        },
        fail: e => {
          console.log(e)
        }
      })
    } else {
      this.syncPriceOperate(base_thrash_config, type);
    }
  },

  syncPriceOperate(base_thrash_config, type) {
    let source = {};
    const ratio = base_thrash_config.money / base_thrash_config.rise;
    if (type == "all" || type == "card") {
      //同步刷卡打水
      let card_thrash_config = this.data.card_thrash_config;
      Object.assign(card_thrash_config, base_thrash_config);
      source.card_thrash_config = card_thrash_config;
    }
    if (type == "all" || type == "coin") {
      //同步投币打水   0.5（五毛）的倍数
      let coin_thrash_config = this.data.coin_thrash_config;
      let money_arr = base_thrash_config.money.toString().split(".");
      if (money_arr.length >= 2 && money_arr[1] !== "") {
        if ("0." + money_arr[1] < 0.5) {
          coin_thrash_config.money = parseInt(money_arr[0]) + 0.5;
        } else if ("0." + money_arr[1] > 0.5) {
          coin_thrash_config.money = parseInt(money_arr[0]) + 1;
        } else {
          coin_thrash_config.money = base_thrash_config.money;
        }
      } else {
        coin_thrash_config.money = base_thrash_config.money;
      }
      coin_thrash_config.rise = base_thrash_config.rise;
      source.coin_thrash_config = coin_thrash_config;
    }
    if (type == "all" || type == "wechat") {
      //同步微信打水
      let wechat_thrash_config = this.data.wechat_thrash_config;
      wechat_thrash_config.forEach(item => {
        if (item.rise) {
          item.money = (item.rise * ratio).toFixed(2) - 0;
        }
      })
      source.wechat_thrash_config = wechat_thrash_config;
    }
    if (type == "all" || type == "alipay") {
      //同步支付宝打水
      let alipay_thrash_config = this.data.alipay_thrash_config;
      alipay_thrash_config.forEach(item => {
        if (item.rise) {
          item.money = (item.rise * ratio).toFixed(2) - 0;
        }
      })
      source.alipay_thrash_config = alipay_thrash_config;
    }
    if (type == "all") {
      source.isTapSyncPrice = true;
    }
    this.setData({
      ...source
    })

  },



  closeTip() {
    clearTimeout(timer);
    this.setData({
      tips: false,
    })
  },

  showTip(e) {
    var type = e.currentTarget.dataset.type;
    let content = "此操作将会将基础价格同步到刷卡打水、投币打水、微信打水、支付宝打水,请谨慎操作";
    if (type == 2) {
      content = "此操作将会将基础价格同步,请谨慎操作";
    }
    clearTimeout(timer);
    this.setData({
      tips: true,
      tipsContent: content,
    }, () => {
      timer = setTimeout(() => {
        this.setData({
          tips: false
        }, () => {
          clearTimeout(timer);
        })
      }, 10000)
    })
  },


  //获取合伙人的加盟商
  getFranchisers(id = "") {
    app.ajax({
      url: "Partner/Franchiser/franchiserList",
      success: res => {
        if (res.data.code == 5000) {
          let source = res.data.data;
          let franchiserIndex = "";
          if (id) {
            let index = source.findIndex(item => item.id == id);
            franchiserIndex = ~index ? index : '';
          }
          this.setData({
            franchisers: source,
            franchiserIndex
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },

  unfoldAdvancedSetting() {
    this.setData({
      is_unfold: !this.data.is_unfold
    })
  },

  formatTime(str) {
    let result = "";
    if (str.length >= 10) {
      result = str.substring(0, 10);
    }
    return result;
  },

  //选择有效期
  chooseLimit(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.currentLimit == index) return;
    this.setData({
      currentLimit: index
    })
  },

  handlePickerTime(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },


  handlePriceInput(e) {
    const value = e.detail.value;
    const dataset = e.currentTarget.dataset;
    this.setData({
      [`price_config[${dataset.index}].${dataset.name}`]: value
    })
  },

  plusPriceConfig(e) {
    const configs = this.data.price_config;
    configs.push({
      recharge: "",
      give: ""
    });
    this.setData({
      price_config: configs
    })
  },

  subtractPriceConfig(e) {
    const index = e.currentTarget.dataset.index;
    const configs = this.data.price_config;
    configs.splice(index, 1);
    this.setData({
      price_config: configs
    })
  },

  //保存
  save() {
    let template_title = this.data.template_title;
    let type = this.data.type;
    if (this.data.isFranchiser && this.data.franchiserIndex === "") {
      app.showToast("请选择加盟商");
      return;
    }
    if (template_title == "") {
      app.showToast("请输入模板名称");
      return;
    }
    if (type == 2) {
      this.savePriceTemplate()
    } else {
      let template = {};
      if (type == 1 || type == 3) {
        let config = this.data.price_config;
        for (let i = 0; i < config.length; i++) {
          if (config[i].recharge === "") {
            app.showToast("充值金额未配置");
            return;
          }
          if (config[i].give === "") {
            app.showToast("赠送金额未配置");
            return;
          }
          template[`money_${parseInt(i)+1}`] = {
            recharge: config[i].recharge,
            give: config[i].give
          }
        }
      }
      let limit = this.data.limits[this.data.currentLimit].value;
      if (limit == 1) {
        let start_time = this.data.start_time;
        let end_time = this.data.end_time;
        if (start_time == "") {
          app.showToast("请选择开始时间");
          return;
        }
        if (end_time == "") {
          app.showToast("请选择结束时间");
          return;
        }
        if (new Date(start_time).getTime() > new Date(end_time).getTime()) {
          app.showToast("结束时间不能小于开始时间");
          return false;
        }
      }
      const data = {
        template,
        template_species: type,
        template_type: limit,
        template_title,
        start_time: limit == 1 ? this.data.start_time : '',
        end_time: limit == 1 ? this.data.end_time : '',
        template_status: this.data.template_status,
      }
      let url = "Partner/Village/addTemplate";
      if (this.data.mode == 2) {
        url = "Partner/Village/editTemplate";
        Object.assign(data, {
          id: this.id
        })
      }
      if (this.data.isFranchiser) {
        Object.assign(data, {
          type: 1,
          partner_id: this.data.franchisers[this.data.franchiserIndex].id
        })
      }
      wx.showLoading();
      app.ajax({
        url,
        data,
        success: res => {
          wx.hideLoading();
          if (res.data.code > 0) {
            app.showToast(res.data.message, "success");
            if (this.from == "middle") {
              //来自middle的处理逻辑 新增就直接返回两个页面  把数据给传递回去，修改就返回上一页，把数据带回去
              if (this.data.mode == 1) {
                let pages = getCurrentPages();
                let page = pages[pages.length - 3];
                let results = res.data.data;
                page.setTemplate(results);
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 2
                  })
                }, 1500)
              } else if (this.data.mode == 2) {
                const results = {
                  data,
                };
                const eventChannel = this.getOpenerEventChannel();
                eventChannel.emit("editTemplatePage", results);
                setTimeout(() => {
                  wx.navigateBack();
                }, 1500)
              }
            } else {
              setTimeout(() => {
                let pages = getCurrentPages();
                let page = pages[pages.length - 2];
                if (page && page.hasOwnProperty("reloadData")) {
                  page.reloadData();
                }
                wx.navigateBack();
              }, 2000);
            }
          } else {
            app.showToast(res.data.message);
          }
        },
        error: e => {
          wx.hideLoading();
          app.showToast("网络错误");
        }
      })
    }
  },


  savePriceTemplate() {
    const base_thrash_config = this.data.base_thrash_config;
    if (base_thrash_config.rise == "") {
      app.showToast("请配置基础价格打水量");
      return false;
    }
    if (base_thrash_config.money == "") {
      app.showToast("请配置基础价格金额");
      return false;
    }
    let base_price = {
      ...base_thrash_config
    };
    if (this.data.mode == 1 && !this.data.isTapSyncPrice) {
      app.showToast("请先同步价格");
      return false;
    }
    let template = {};
    let card_thrash_config = this.data.card_thrash_config;
    if (card_thrash_config.rise == "") {
      app.showToast("刷卡打水量未配置");
      return false;
    }
    if (card_thrash_config.money == "") {
      app.showToast("刷卡打水金额未配置");
      return false;
    }
    if (card_thrash_config.withholding_fee_rise === "") {
      app.showToast("刷卡打水预扣费取水量未配置");
      return false;
    }
    template.card = {
      rise: card_thrash_config.rise,
      money: card_thrash_config.money,
      water_quantity: card_thrash_config.withholding_fee_rise,
    };

    let coin_thrash_config = this.data.coin_thrash_config;
    if (coin_thrash_config.rise == "") {
      app.showToast("投币打水量未配置");
      return false;
    }
    if (coin_thrash_config.money == "") {
      app.showToast("投币打水金额未配置");
      return false;
    }
    if (coin_thrash_config.coin_upper_limit === "") {
      app.showToast("投币金额上限未配置");
      return false;
    }
    if (coin_thrash_config.withholding_fee_rise === "") {
      app.showToast("投币打水预扣费取水量未配置");
      return false;
    }
    template.coin = {
      rise: coin_thrash_config.rise,
      money: coin_thrash_config.money,
      coin_money: coin_thrash_config.coin_upper_limit,
      water_quantity:coin_thrash_config.withholding_fee_rise
    };
    let wechat = [];
    let wechat_thrash_config = this.data.wechat_thrash_config;
    for (let i = 0; i < wechat_thrash_config.length; i++) {
      if (wechat_thrash_config[i].rise == "") {
        app.showToast(`微信打水第${i+1}项打水量未配置`);
        return false;
      }
      if (wechat_thrash_config[i].money == "") {
        app.showToast(`微信打水第${i+1}项金额未配置`);
        return false;
      }
      wechat.push({
        rise: wechat_thrash_config[i].rise,
        money: wechat_thrash_config[i].money
      });
    }
    template.wx = wechat;
    let alpay = [];
    let alipay_thrash_config = this.data.alipay_thrash_config;
    for (let i = 0; i < alipay_thrash_config.length; i++) {
      if (alipay_thrash_config[i].rise == "") {
        app.showToast(`支付宝打水第${i+1}项打水量未配置`);
        return false;
      }
      if (alipay_thrash_config[i].money == "") {
        app.showToast(`支付宝打水第${i+1}项金额未配置`);
        return false;
      }
      alpay.push({
        rise: alipay_thrash_config[i].rise,
        money: alipay_thrash_config[i].money
      });
    }
    template.al = alpay;
    let limit = this.data.limits[this.data.currentLimit].value;
    if (limit == 1) {
      let start_time = this.data.start_time;
      let end_time = this.data.end_time;
      if (start_time == "") {
        app.showToast("请选择开始时间");
        return;
      }
      if (end_time == "") {
        app.showToast("请选择结束时间");
        return;
      }
      if (new Date(start_time).getTime() > new Date(end_time).getTime()) {
        app.showToast("结束时间不能小于开始时间");
        return false;
      }
    }
    const data = {
      template,
      base_price,
      template_type: limit,
      template_title: this.data.template_title,
      start_time: limit == 1 ? this.data.start_time : '',
      end_time: limit == 1 ? this.data.end_time : '',
      template_status: this.data.template_status,
    }
    let url = "Partner/Village/addWaterTemplate";
    if (this.data.mode == 2) {
      Object.assign(data, {
        template_id: this.id
      })
    }
    if (this.data.isFranchiser) {
      Object.assign(data, {
        type: 1,
        partner_id: this.data.franchisers[this.data.franchiserIndex].id
      })
    }
    wx.showLoading();
    app.ajax({
      url,
      data,
      success: res => {
        wx.hideLoading();
        if (res.data.code > 0) {
          app.showToast(res.data.message, "success");
          if (this.from == "middle") {
            //来自middle的处理逻辑 新增就直接返回两个页面  把数据给传递回去，修改就返回上一页，把数据带回去
            if (this.data.mode == 1) {
              let pages = getCurrentPages();
              let page = pages[pages.length - 3];
              let results = res.data.data;
              page.setTemplate(results);
              setTimeout(() => {
                wx.navigateBack({
                  delta: 2
                })
              }, 1500)
            } else if (this.data.mode == 2) {
              const results = res.data.data;
              const eventChannel = this.getOpenerEventChannel();
              eventChannel.emit("editTemplatePage", results);
              setTimeout(() => {
                wx.navigateBack();
              }, 1500)
            }
          } else {
            setTimeout(() => {
              let pages = getCurrentPages();
              let page = pages[pages.length - 2];
              if (page && page.hasOwnProperty("reloadData")) {
                page.reloadData();
              }
              wx.navigateBack();
            }, 2000);
          }
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误");
      }
    })

  },

})